import logging
import logging.handlers
import time

# 定义日志生成器
dev_logger = logging.getLogger("develop_log")
prod_logger = logging.getLogger("product_log")

record_logger = logging.getLogger('test_recorder')

# 设置日志处理等级
record_logger.setLevel(logging.INFO)
dev_logger.setLevel(logging.DEBUG)
prod_logger.setLevel(logging.WARNING)

# 创建日志处理器
consoleHandler = logging.StreamHandler()  # 输出到控制台
consoleHandler.setLevel(logging.DEBUG)

"""
dev_filename= 'devlog.log'
prod_filename= 'prodlog.log'
mode = 'a'
encoding='utf-8'
delay=False
"""
# 设置循环日志记录
fileHandler_dev = logging.handlers.RotatingFileHandler(
    filename="./logs/devlog.log",
    mode="a",
    maxBytes=1024 * 1024,
    backupCount=5,
    encoding="utf-8",
    delay=False,
)
# fileHandler_dev.setLevel(logging.INFO)
fileHandler_dev.setLevel(logging.DEBUG)

# 设置生产日志记录
fileHandler_prod = logging.handlers.RotatingFileHandler(
    filename="./logs/prodlog.log",
    mode="a",
    maxBytes=1024 * 1024,
    backupCount=5,
    encoding="utf-8",
    delay=False,
)
fileHandler_prod.setLevel(logging.WARNING)

# 设置测试情况记录存档
fileHandler_record = logging.handlers.RotatingFileHandler(
    filename="./logs/record.csv",
    mode="a",
    maxBytes=1024 * 1024,
    backupCount=5,
    encoding="utf-8",
    delay=False, 
)

# 设置Formatters格式
formatter = logging.Formatter(
    "%(asctime)s|%(levelname)8s|%(filename)s:%(lineno)s|%(message)s"
)


record_formatter = logging.Formatter(
    "%(asctime)s,%(lineno)s,%(message)s"
)

# 给处理器设置格式
consoleHandler.setFormatter(formatter)
fileHandler_dev.setFormatter(formatter)
fileHandler_prod.setFormatter(formatter)
fileHandler_record.setFormatter(record_formatter)

# 给记录器设置处理器
prod_logger.addHandler(fileHandler_prod)
prod_logger.addHandler(consoleHandler)

dev_logger.addHandler(fileHandler_dev)
dev_logger.addHandler(consoleHandler)

record_logger.addHandler(fileHandler_record)


# FIXME  设置过滤器,如有必要
# 以下设置可以将有an的日志忽略掉
# ft = logging.Filter('an')
# prod_logger.addFilter(ft)



##############################数据库###############################
import sqlalchemy
from sqlalchemy.orm import declarative_base, sessionmaker
from datetime import datetime
engine = sqlalchemy.create_engine('sqlite:///./logs/log_record_db.sqlite3',echo=True)
# mysql 数据库连接
# engine = sqlalchemy.create_engine('mysql://admin_00001:admin_00001@127.0.0.1:3306/sqlalchemy_20240226', echo=True)
# 创建会话类
Session = sessionmaker(bind=engine)


Base = declarative_base()
class LogRecord(Base):
    __tablename__ = 'log_record'
    id = sqlalchemy.Column(sqlalchemy.Integer,autoincrement=True, primary_key=True)
    create_time = sqlalchemy.Column('创建时间',sqlalchemy.DateTime, default=datetime.now)
    vin = sqlalchemy.Column('VIN号',sqlalchemy.String, nullable=False)
    status = sqlalchemy.Column('状态',sqlalchemy.String, nullable=False)
    message = sqlalchemy.Column(sqlalchemy.Text)# 创建表

def create_table():
##############################
# 手工命令创建，不推荐
    if 0:
        conn = engine.connect()
        conn.execute('''
            CREATE TABLE IF NOT EXISTS record(
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                time TEXT,
                line INTEGER,
                message TEXT
            )
        ''')
        conn.close()
##############################

    Base.metadata.create_all(engine)


def insert_record(vin, status, message):
    session = Session()
    record = LogRecord(vin=vin, status=status, message=message)
    session.add(record)
    session.commit()
    session.close()

if __name__ == "__main__":

    # create_table()
    insert_record('vin_00001', 'info', '这是一条测试记录')


    if 0:
        for i in range(30):
            prod_logger.debug("这是prod_logger的 debug日志输出")
            prod_logger.info("这是prod_logger的 info日志输出")
            prod_logger.warning("这是prod_logger的 warn日志输出")
            prod_logger.error("这是prod_logger的 error日志输出")

            dev_logger.debug("这是dev_logger的 debug日志输出")
            dev_logger.info("这是dev_logger的 info日志输出")
            dev_logger.warning(" 这是dev_logger的 warn日志输出")
            dev_logger.error("这是dev_logger的 error日志输出")
            time.sleep(0.1)
